package com.sinheldrin.musicplayer.library
{
	import com.sinheldrin.musicplayer.fields.FieldsController;
	import com.sinheldrin.musicplayer.music.Music;
	import com.sinheldrin.musicplayer.music.MusicCollection;
	import com.sinheldrin.musicplayer.music.Playlist;
	import com.sinheldrin.musicplayer.reader.XmlReader;
	import com.sinheldrin.musicplayer.writer.XmlWriter;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.collections.ArrayCollection;

	public class LibraryController extends MusicCollection
	{
		public function LibraryController()
		{
			super();
			
			_fields = new FieldsController();
		}
		
		private var _fields:FieldsController = null;
		public function get fields():FieldsController
		{
			return _fields;
		}
		
		private var _maxId:int = 0;
		
		public function addNewMusic(music:Music):void
		{
			music.id = ++_maxId;
			super.addMusic(music);
		}
		
		override public function addMusic(music:Music):void
		{
			super.addMusic(music);
			if (music.id > _maxId)
				_maxId = music.id;
		}

		public function load():void
		{
			fields.load();
			
			var reader:XmlReader = new XmlReader();
			var file:File = File.applicationStorageDirectory.resolvePath("library.xml");
			if (file.exists)
				reader.readLibrary(this, file, fields);
		}
		
		public function save():void
		{
			fields.save();
			
			var writer:XmlWriter = new XmlWriter();
			writer.writeLibrary(this, File.applicationStorageDirectory, "library.xml");
		}
		
		public function toPlaylist():Playlist
		{
			var playlist:Playlist = new Playlist();
			for each (var music:Music in musics)
			{
				playlist.addMusic(music);
			}
			return playlist;
		}
	}
}